package com.thorqq.translation;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.thorqq.translation.api.TransApi;
import com.thorqq.translation.api.TransBaidu;
import com.thorqq.translation.api.TransGoogle;
import com.thorqq.translation.utils.Log;
import com.thorqq.translation.utils.Utils;

public class Main
{
	

	public static void main(String[] argv)
	{
		Log.init();
		
		//检查参数
		if(argv.length < 1)
		{
			Log.e("Please input file path");
			return;
		}
		
		String filename = argv[0];

		new Main().translate(filename);

	}
	
	public void translate(String filename)
	{
		//读入文件
		List<String> article = Utils.readFileByLines(filename);
		if(article.size() == 0)
		{
			Log.w("No text to translate");
			return;
		}
		
		Log.i(String.format("Begin to translate file[%s], %d lines", filename, article.size()));

    	platformTrans(filename, article, new TransBaidu());
    	platformTrans(filename, article, new TransGoogle());
	}
	
	public void platformTrans(String filename, List<String> article, TransApi translator)
	{
		List<String> articleBaidu = new ArrayList<String>();
    	int line = 0;
		for(String src : article)
		{
			try
	        {
				String dst = translator.enToZh(src);
				articleBaidu.add(dst);
				Log.d(String.format("Translate line %d/%d\n%s\n====>\n%s", ++line, article.size(), src, dst));
	        }
	        catch (Exception e)
	        {
		        e.printStackTrace();
		        Log.ex(e);
	        }
		}

		//写文件
		File file = new File(filename);
		String name = file.getAbsolutePath();
		int dotIndex = name.lastIndexOf(".");
		String postfix = name.substring(dotIndex);
		String prefix = name.substring(0, dotIndex);
		String newfilename = prefix + "."  + translator.getVendor() + postfix;
		Utils.writeFileByLines(articleBaidu, newfilename);
        
		Log.i("Success to write artile to file: " + newfilename);
	}
}
